package com.cdvtc.forum_system.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@WebServlet("/uploadPost")
@MultipartConfig
public class UploadPostServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 获取表单数据
            String title = request.getParameter("postTitle");
            String content = request.getParameter("postContent");
            String category = request.getParameter("category");

            // 验证必填字段
            if (title == null || title.trim().isEmpty() ||
                    content == null || content.trim().isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"error\": \"标题和内容不能为空\"}");
                return;
            }

            // 处理上传的文件
            Collection<Part> fileParts = request.getParts();
            List<String> uploadedFiles = new ArrayList<>();

            for (Part filePart : fileParts) {
                if (filePart.getName().equals("fileInput") && filePart.getSize() > 0) {
                    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
                    String uploadPath = getServletContext().getRealPath("") + File.separator + "uploads";

                    // 确保上传目录存在
                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdir();
                    }

                    // 生成唯一文件名
                    String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;
                    String filePath = uploadPath + File.separator + uniqueFileName;

                    // 保存文件
                    try (InputStream fileContent = filePart.getInputStream()) {
                        Files.copy(fileContent, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
                    }

                    uploadedFiles.add(uniqueFileName);
                }
            }

            // 这里应该调用业务逻辑处理帖子数据
            // 例如: postService.createPost(title, content, category, uploadedFiles);

            // 返回成功响应
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write("{\"success\": true, \"message\": \"帖子发布成功\"}");

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"error\": \"服务器内部错误: " + e.getMessage() + "\"}");
        }
    }
}